package Controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JList;
import Entities.InitiateSaleEntity;
import GUI.InitiateSaleGUI;
import GUI.WorkDivisionGUI;
import Server.RsWraper;
import Server.Tuple;



/**
 * The Class InitiateSaleController.
 * Controller for sale initiation activity.
 */
public class InitiateSaleController implements Validate,Observer{
	
	/** The initiate sale entity. */
	private InitiateSaleEntity initiateSaleEntity;
	
	/** The initiate sale gui. */
	private InitiateSaleGUI initiateSaleGUI;
	
	/** The previous controller. */
	private MarketingManagerController prev;
	
	/** The date. */
	private Date date; 
	
	/** The empty list flag. */
	private int emptyListFlag=0;
	
	/** The operation. */
	private int operation;
	
	/**
	 * Instantiates a new initiate sale controller.
	 *
	 * @param initiateSaleEntity the initiate sale entity
	 * @param initiateSaleGUI the initiate sale gui
	 */
	public InitiateSaleController(InitiateSaleEntity initiateSaleEntity,InitiateSaleGUI initiateSaleGUI) {
		this.initiateSaleEntity = initiateSaleEntity;
		this.initiateSaleGUI = initiateSaleGUI;
		ClientController.setObserver(this);
		addMpToList();	
		this.initiateSaleGUI.addOKActionListener(new OkListener());
		this.initiateSaleGUI.addBackActionListener(new BackListener());
		this.initiateSaleGUI.setVisible(true);
	}

	/**
	 * Adds the marketing patterns to the list.
	 */
	private void addMpToList() {
		operation=0;
		String query = "SELECT mp.mpid,mp.pid,mp.pname,mp.age,mp.livingarea,mp.importancerank,mp.interestlevel FROM mp";
		try {
			ClientController.observableClient.sendToServer(query);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}

	/**
	 * The listener interface for receiving ok events.
	 * The class that is interested in processing a ok
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addOkListener<code> method. When
	 * the ok event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see OkEvent
	 */
	class OkListener implements ActionListener
	{

		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			if(validateInput())
			{
				String[]subject=initiateSaleGUI.getMpList().getSelectedValue().split(",");
				initiateSaleEntity.setMpid(subject[0]);
				initiateSaleEntity.setPid(subject[1]);
				initiateSaleEntity.setName(subject[2]);
				initiateSaleEntity.setAge(Integer.parseInt(subject[3]));
				initiateSaleEntity.setLivingArea(subject[4]);
				initiateSaleEntity.setImportancerank(Integer.parseInt(subject[5]));
				initiateSaleEntity.setInterestlevel(Integer.parseInt(subject[6]));
				initiateSaleEntity.setDate(initiateSaleGUI.getDateTf().getText());
				initiateSaleEntity.setPeriod(initiateSaleGUI.getPeriodTf().getText());			
				String query = "SELECT sales.sid FROM sales WHERE sales.mpid= '"+Integer.parseInt(initiateSaleEntity.getMpid())+"' AND sales.date= '"+initiateSaleEntity.getDate()+"' AND sales.period= '"+initiateSaleEntity.getPeriod()+"' AND sales.location= '"+initiateSaleEntity.getLivingArea()+"'" ;
				try {
					operation=1;
					ClientController.observableClient.sendToServer(query);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		
	}
	
	/**
	 * The listener interface for receiving back events.
	 * The class that is interested in processing a back
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addBackListener<code> method. When
	 * the back event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see BackEvent
	 */
	class BackListener implements ActionListener
	{

		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent arg0) {
			LoginController.mainWindow.setTitle("Marketing manager");
			LoginController.mainWindow.setContentPane(prev.getMarketingManagerGui());
		}
	
	}
	
	/* (non-Javadoc)
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	@Override
	public void update(Observable o, Object arg) {
	
		if(arg.toString().equals("empty query")||arg.toString().equals("error"))
		{
			if(operation==0){
			initiateSaleGUI.displayWarningMessage("There are not any existing marketing patterns");
			emptyListFlag=1;
			}
			if(operation==1)
			{
				initiateSaleGUI.displayMessage("Initiating sale succeded");
				WorkDivisionGUI workDivisionGUI = new WorkDivisionGUI();
				new WorkDivisionController(workDivisionGUI,initiateSaleEntity).setPrev(InitiateSaleController.this);;
				LoginController.mainWindow.setContentPane(workDivisionGUI);
			}
		}
		else if(operation==0)
		{
			date = new Date();
			int year = date.getYear();
			year = year + 1900;

			ArrayList<Tuple> tuples = ((RsWraper)arg).getRows();//appends all mp list
					
			String[] mp = new String[tuples.size()];
			for(int i=0;i<tuples.size();i++)
				mp[i]=tuples.get(i).get("MPID")+","+tuples.get(i).get("PID")+","+tuples.get(i).get("PNAME")+","+tuples.get(i).get("AGE")+","+tuples.get(i).get("LIVINGAREA")+","+tuples.get(i).get("IMPORTANCERANK")+","+tuples.get(i).get("INTERESTLEVEL");
			initiateSaleGUI.getMpList().setListData(mp);
			
		}
		else if(operation==1)
		{
				initiateSaleGUI.displayWarningMessage("The same sale is already exists");
				operation=2;
		}
		
	}

	/* (non-Javadoc)
	 * @see Controllers.Validate#validateInput()
	 */
	@Override
	public boolean validateInput() {
		JList<String> subject=initiateSaleGUI.getMpList();
		String date=initiateSaleGUI.getDateTf().getText();
		String period=initiateSaleGUI.getPeriodTf().getText();
		
		if(emptyListFlag==1||subject.isSelectionEmpty()||date.contains("_")||period.equals(""))
		{
			initiateSaleGUI.displayWarningMessage("Please fill all the missing fields.");
			return false;
		}
		else
		{
			try
			{
				Integer.parseInt(period);
			}
			catch (NumberFormatException e)
			{
				initiateSaleGUI.displayWarningMessage("Error:illeagel characters in id field.");
				return false;
			}
			if(Integer.parseInt(date.substring(6,10))>=2015)
			{
				if(Integer.parseInt(date.substring(3,5))<13&&Integer.parseInt(date.substring(3,5))>-1)
				{
					if(Integer.parseInt(date.substring(0,2))<32&&Integer.parseInt(date.substring(0,2))>0)
					{
						return true;
					}
					else
						return false;
				}
				else
					return false;
			}
			else
				return false;
		}
	}
	
	/**
	 * Sets the previous controller.
	 *
	 * @param prev the new previous controller
	 */
	public void setPrev(MarketingManagerController prev) {
		this.prev = prev;
	}

	/**
	 * Gets the initiate sale entity.
	 *
	 * @return the initiate sale entity
	 */
	public InitiateSaleEntity getInitiateSaleEntity() {
		return initiateSaleEntity;
	}

	/**
	 * Sets the initiate sale entity.
	 *
	 * @param initiateSaleEntity the new initiate sale entity
	 */
	public void setInitiateSaleEntity(InitiateSaleEntity initiateSaleEntity) {
		this.initiateSaleEntity = initiateSaleEntity;
	}

	/**
	 * Gets the initiate sale gui.
	 *
	 * @return the initiate sale gui
	 */
	public InitiateSaleGUI getInitiateSaleGUI() {
		return initiateSaleGUI;
	}

	/**
	 * Sets the initiate sale gui.
	 *
	 * @param initiateSaleGUI the new initiate sale gui
	 */
	public void setInitiateSaleGUI(InitiateSaleGUI initiateSaleGUI) {
		this.initiateSaleGUI = initiateSaleGUI;
	}

	/**
	 * Gets the date.
	 *
	 * @return the date
	 */
	public Date getDate() {
		return date;
	}

	/**
	 * Sets the date.
	 *
	 * @param date the new date
	 */
	public void setDate(Date date) {
		this.date = date;
	}

	/**
	 * Gets the previous controller.
	 *
	 * @return the previous controller
	 */
	public MarketingManagerController getPrev() {
		return prev;
	}
	
}
